package com.cskaoyan.market.service.admin.impl;

import com.cskaoyan.market.db.domain.MarketPermission;
import com.cskaoyan.market.db.domain.MarketPermissionExample;
import com.cskaoyan.market.db.domain.MarketRole;
import com.cskaoyan.market.db.domain.MarketRoleExample;
import com.cskaoyan.market.db.mapper.MarketPermissionMapper;
import com.cskaoyan.market.db.mapper.MarketRoleMapper;
import com.cskaoyan.market.service.admin.MarketRoleService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName MarketRoleServiceImpl
 * @Description
 * @Author MZ
 * @Date 2023/5/24 9:17
 */
@Service
public class MarketRoleServiceImpl implements MarketRoleService {
    @Autowired
    MarketRoleMapper roleMapper;
    @Autowired
    MarketPermissionMapper permissionMapper;
    @Override
    public List<MarketRole> getRoleList(Integer page, Integer limit, String sort, String order) {

        MarketRoleExample roleExample = new MarketRoleExample();
        roleExample.or().andDeletedEqualTo(false);
        roleExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page,limit);
        List<MarketRole> roles = roleMapper.selectByExample(roleExample);

        return roles;
    }

    @Override
    public List<MarketRole> options() {

        MarketRoleExample marketRoleExample = new MarketRoleExample();
        marketRoleExample.or().andLogicalDeleted(true);
        PageHelper.startPage(1,6);
        List<MarketRole> marketRoles = roleMapper.selectByExampleSelective(marketRoleExample, MarketRole.Column.id, MarketRole.Column.name);

        return marketRoles;
    }

    @Override
    public Set<String> getPermissions(Integer roleId) {

        MarketPermissionExample permissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = permissionExample.or().andDeletedEqualTo(false);
        if (roleId == 1){
            // 所有权限
            criteria.andRoleIdNotEqualTo(roleId);
        }else {
            // 获得相应的权限
            criteria.andRoleIdNotEqualTo(roleId);
        }
        List<MarketPermission> permissions = permissionMapper.selectByExample(permissionExample);
        Set<String> assignedPermissions = new HashSet<>();
        for (MarketPermission permission : permissions) {
            assignedPermissions.add(permission.getPermission());
        }

        return assignedPermissions;
    }
}
